// Promise 链式异步调用
function resolvePromise(x, resolve, reject){
    if( x instanceof MyPromise){
        // 执行 x, 调用Then方法，目的是将其状态变为fulfilled或者rejected
        // x.then(value => resolve(value), reason => reject(reason))
        // 简化之后
        x.then(resolve,reject);
    }else{
        resolve(x)
    }
}


const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';

class MyPromise{
    constructor(executor){
        this.status = PENDING;
        this.value = undefined;
        this.reason = undefined;

        this.successCallbackList = [];
        this.failedCallbackList = [];

        let resolve = (value) => {
            if(this.status === PENDING){
                this.status = FULFILLED;
                this.value = value;
                this.successCallbackList.forEach(fn => fn());
            }
        }

        let reject = (reason) => {
            if(this.status === PENDING){
                this.status = REJECTED;
                this.reason = reason;
                this.failedCallbackList.forEach(fn => fn());
            }
        }

        try{
            executor(resolve,reject)
        }catch(error){
            reject(error)
        }
    }

    then(onSuccessFunc, onFailedFunc){
        const promise2 = new MyPromise((resolve,reject) => {
            if(this.status === FULFILLED){
                const x = onSuccessFunc(this.value);
                resolvePromise(x, resolve,reject)
            }else if(this.status === REJECTED){
                onFailedFunc(this.reason);
            }else if(this.status === PENDING){
                this.successCallbackList.push(() => onSuccessFunc(this.value));
                this.failedCallbackList.push(() => onFailedFunc(this.reason));
            }
        });
        return promise2;
    }
}


new MyPromise((resolve) => {
    resolve(10)
}).then((data) => {
    console.log(data);
    return new MyPromise((resolve) =>{
        resolve(20)
    })
}).then((res) => {
    console.log(res);
})

